package com.googlecode.astoolkit.modules.browser {
	
	import com.asual.swfaddress.SWFAddress;
	import com.asual.swfaddress.SWFAddressEvent;
	import com.googlecode.astoolkit.events.FrankyEvents;
	import com.googlecode.astoolkit.vo.ParamsObject;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class Browser extends EventDispatcher {

		private static var _instance:Browser;
		private var _path:String;
		private var _pathNames:Array = [];
		private var _params:Array = [];
		private var _paramNames:Array = [];

		public function Browser(singletonenforcer:SingletonEnforcer) {
			if (singletonenforcer == null) {
				throw new Error("Browser es un Singleton. Para acceder a una instancia hacedlo mediante Browser.getInstance()");
			}
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, urlChange);
		}

		public static function getInstance():Browser {
			if (!_instance) {
				_instance = new Browser(new SingletonEnforcer());
			}
			return _instance;
		}
		
		//
		public function goto(path:String, params:Object=null):void{
			var cadenaParams:String = "";
			if(params){
				for (var p:* in params) {
					var cadena:String = params[p];
					cadenaParams += String(p) + "=" + params[p] + "/";
				}
				//trace("cadenaParams-->" + cadenaParams);
			}
			SWFAddress.setValue("/"+path+"/"+cadenaParams);
		}
		
		//
		public static function setTitle(title:String):void{
			SWFAddress.setTitle(title);			
		} 
		
		public static function back():void{
			SWFAddress.back();
		}
		
		
		
		//
		private function urlChange(e:SWFAddressEvent):void{
			var prevPath:String = _path;
			var prevParams:String = params.toString();
			_path = e.path.slice(1, -1);
			//trace("PATH REAL--><" + _path + ">");
			
			// Recojo los parametros si existen, los quito del path y los guardo a parte
			var indexParams:int = e.path.indexOf("=");
			if(indexParams > -1){
				indexParams = _path.lastIndexOf("/", indexParams);
				var parameters:String = _path.substring(indexParams+1); 
				_params = parameters.split("/");
				_path = _path.substring(0, indexParams);
			}
			_pathNames = _path.split("/");
			
			setTitle(_pathNames.join(" > "));
			
			if(_path != prevPath){
				dispatchEvent(new Event(FrankyEvents.PATH_CHANGED));
			}
			
			if(params.toString() != prevParams){
				dispatchEvent(new Event(FrankyEvents.PARAMS_CHANGED));
			}
			
		}
		
		// Getter y Setter de _path
		public function get path():String{
		     return _path;
		}
		// Getter y Setter de _pathNames
		public function get pathNames():Array{
		     return _pathNames;
		}
		// Getter y Setter de _params
		public function get params():ParamsObject{
			var obj:Object = new Object();
			for each(var p:String in _params){
				var pair:Array = p.split("=");
				obj[pair[0]] = pair[1];
			}
		    return new ParamsObject(obj);
		}
	}
}
class SingletonEnforcer{}
